'use strict'

var mongoose = require('mongoose')
var Art = mongoose.model('Art')
var Category = mongoose.model('Category')
var Comment = mongoose.model('Comment')
var _ = require('underscore')
var fs = require('fs')
var path = require('path')
var config = require('../../config');
var wechatApi = config.getWechat();

// detail page
exports.detail = function *(next) {
  var id = this.params.id
  var flag = this.req.url.indexOf('one')>-1
  var muban = flag? 'pages/addArticle': 'pages/detailArticle'
  console.log(flag)
  var article = yield Art.findOne({_id: id}).exec()
  var categories = yield Category.find({}).exec()
  var comments = yield Comment
      .find({article: id})
      .populate('from', 'name path')
      .populate('reply.from reply.to', 'name path')
      .exec()
  yield this.render(muban, {
    title: '文章详情页',
    article: article,
    categories: categories,
    comments: comments
  })
}

// admin new page
exports.new = function *(next) {
  var categories = yield Category.find({}).exec();
    yield this.render('pages/addArticle', {
      title: '哎优后台录入页',
      categories: categories,
      article: {}
    })
}

// admin update page
exports.update = function *(next) {
  var id = this.params.id

  if (id) {
    var movie = yield Art.findOne({_id: id}).exec();
    var categories = yield Category.find({}).exec();
    yield this.render('pages/addArticle', {
      title: '哎优后台更新页',
      article: movie,
      categories: categories
    })
  }
}

var util = require('../../libs/util')

// admin post movie
exports.save = function *(next) {
  var articleObj = this.request.body || {}
  var _article

  if (articleObj._id) {
    var article = yield Art.findOne({_id: articleObj._id}).exec()
  
    _article = _.extend(article, articleObj)
    var categoryName = articleObj.categoryName
    if (categoryName) {
      var category = new Category({
        name: categoryName,
        articles: [article._id]
      })

      category = yield category.save()
      _article.category = category._id
    }
    yield _article.save()
    this.body = {success:true,id: article._id}
  }
  else {
    _article = new Art(articleObj)

    var categoryId = articleObj.category
    var categoryName = articleObj.categoryName
    article = yield _article.save()
    if (categoryName) {
      var category = new Category({
        name: categoryName,
        articles: [article._id]
      })

      category = yield category.save()
      article.category = category._id
      yield article.save()
      this.body = {success:true,id: article._id}
    }else if(categoryId){
      var category = yield Category.findOne({_id:categoryId}).exec()
      category.articles.push(article._id)

      yield category.save()
      this.body = {success:true,id: article._id}
    }
  }
}

// list page
exports.list = function *(next) {
  var articles = yield Art.find({})
    .populate('category', 'name')
    .exec()

    yield this.render('pages/list', {
      title: 'imooc 列表页',
      articles: articles
    })
}

// list page
exports.del = function *(next) {
  var id = this.query.id

  if (id) {
    try{
      Art.remove({_id: id}).exec()
      this.body = {success: 1}
    }
    catch(err){
      console.log(err)
      this.body = {success: 0}
    }
    
  }
}

exports.upload = function *(next){
  //console.log(this.request.body)
  var provider = this.query.provider
  var posterData = this.request.body.files.imgFile || this.request.body.files.file
  var filePath = posterData.path
  var name = posterData.name
  //console.log(filePath)

  var fname = filePath.replace("public\\upload\\", "").replace("public/upload/", "");
  var newPath = path.join(__dirname, '../../', '/public/upload/' + fname)
  if(provider==='aliyun'){
    var body = yield wechatApi.uploadAliOss(name,newPath)
  }else if(provider==='wxtext'){
    var body = yield wechatApi.uploadPermMaterial('pic',newPath)
  }else{
    var body = yield wechatApi.uploadPermMaterial('image',newPath)
  }
  body.error = 0;
  fs.unlink(newPath)
  this.body = body
}
exports.sendAll = function*(next){
  var id = this.query.id
  var article = yield Art.findOne({_id: id }).exec()
  var data ={
    "articles": [{
         "title": article.title,
         "thumb_media_id": article.poster,
         "author": '',
         "digest": article.abstract,
         "show_cover_pic": 1,
         "content": article.text,
         "content_source_url": article.sourceurl
      }
   ]
  }
  var media = yield wechatApi.uploadPermMaterial('news',data)
  var openIDs = yield wechatApi.getUserOpenIds()
  var result = yield wechatApi.massSendMsg('mpnews',{media_id: media.media_id},openIDs.data.openid[0])
  article.isSend = true
  yield article.save()
  this.body = result
}